/*!
 * jquery.jCouch. The jQuery Couch plugin
 *
 * Copyright (c) 2012 Arvind Bhardwaj
 * http://webspeaks.in
 *
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Version : 0.1
 * 
 * all CSS sizing (width,height) is done in pixels (px)
 */

 (function($){
	//Stores the current couch element
	var thisEl = '';
	$.fn.jCouch = function(options){

		var defaults = {
			target: '',
			amplify: 0
		}

		var o = $.extend(defaults, options);

		$(this).click(function(){
			thisEl = $(this);
			thisEl.each(function(){
				$(this).hide();
			})
			if ($.trim(o.target) == '') {
				return false;
			}
			targets = o.target.split(',');

			var couchBgHtml = '<div id="couchBg">';
			couchBgHtml += '<div id="couchToolbar"><a href="#" id="couchToolbar_Close" title="Switch to the original layout">[esc]</a></div>';
			couchBgHtml += '<div id="couchData"></div>';
			couchBgHtml += '</div>';

			$('body').append(couchBgHtml);
			$('#couchBg').show();
			if (exists(o.bgColor)) {
				$('#couchBg').css('background-color', o.bgColor);
			}
			if (exists(o.width)) {
				$('#couchData').css('width', o.width);
			}

			var innerHtml = '';
			for (x in targets) {
				//Get the HTML element with its parent wrapper
				var html = $($(targets[x])).clone().wrap('<p>').parent().html();
				innerHtml += html;
			}
			$('#couchData').html(innerHtml);

			if (isNumber(o.amplify) && o.amplify > 0) {
				for (x in targets) {
					var el = $('#couchData > '+targets[x]);
					var fSize = parseFloat(el.css('font-size'));
					var amplFSize = parseFloat(fSize) + parseFloat(fSize * o.amplify);
					el.css({'font-size' : amplFSize + 'px'});
				}
			}

			//Set the height of couch
			var couchHeight = parseFloat($('body').height()) + 100;
			$('#couchBg').css('height', couchHeight + 'px');
			$("html, body").animate({ scrollTop: 0 }, "slow");
		});

		function closeCouch() {
			thisEl.each(function(){
				$(this).show();
			})
			$('#couchBg').hide();
		}

		$('#couchToolbar_Close').live('click', closeCouch);
		$(document).keyup(function(e){
			//Disable couch on pressing `ESC`
			if(e.keyCode==27) {
				closeCouch();
			}
		});

		function exists(val) {
			if (typeof(val) != 'undefined' && $.trim(val) != '') {
				return true;
			}
			return false;
		}
		function isNumber(n) {
			return !isNaN(parseFloat(n)) && isFinite(n);
		}
	};
})(jQuery);